package com.atguigu.stack;

import java.util.Scanner;

/**
 * @author 龍
 */
public class ArrayStackDemo {
    public static void main(String[] args) {
        ArrayStack stack = new ArrayStack(4);
        char key = ',';
        boolean loop = true;
        Scanner scanner = new Scanner(System.in);
        while (loop) {
            System.out.println("s--show:展示栈");
            System.out.println("e--exit:退出程序");
            System.out.println("p--push:表示添加数据到栈");
            System.out.println("o--pop:表示从栈中取出数据");
            System.out.println("请输入需要做的选项");
            key = scanner.next().charAt(0);
            switch (key) {
                case 's':
                    stack.list();
                    break;
                case 'p':
                    System.out.println("请输入需要存放的值");
                    stack.push(scanner.nextInt());
                    break;
                case 'o':
                    try {
                        int value = stack.pop();
                        System.out.println("出栈的数据" + value);
                    } catch (Exception e) {
                        System.out.println(e.getMessage());
                    }
                    break;
                case 'e':
                    scanner.close();
                    loop = false;
                    break;
                default:
                    break;
            }

        }
        System.out.println("程序退出");

    }
}

class ArrayStack {
    private int maxSize;
    private int[] stack;
    private int top = -1;
    /**
     * 构造器
     */
    public ArrayStack(int maxSize) {
        this.maxSize = maxSize;
        stack = new int[this.maxSize];
    }

    /**
     * 栈满
     */
    public boolean isFull() {
        return top == maxSize - 1;
    }

    /**
     * 栈空
     */
    public boolean isEmpty() {
        return top == -1;
    }

    /**
     * 入栈
     */
    public void push(int value) {
        if (isFull()) {
            System.out.println("栈已经满了！！！");
            return;
        }
        top++;
        stack[top] = value;
    }

    /**
     * 出栈
     */
    public int pop() {
        if (isEmpty()) {
            throw new RuntimeException("栈已经空了！！！");
        }
        int value = stack[top];
        top--;
        return value;
    }

    /**
     * 遍历栈
     */
    public void list() {
        if (isEmpty()) {
            System.out.println("栈是空的！！！");
        }
        for (int i = top; i >= 0; i--) {
            System.out.println("stack[" + i + "]" + stack[i]);
        }
    }
}
